package com.lihepeng.leecode.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者模型 第一
 * 两个线程一个+1 一个 -1 循环 5伦
 *
 */
class Resource{
    private int num = 0;
    private ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    // 防止虚拟唤醒
    public void incr() {
        lock.lock();
        try {
            while (num !=0) {
                condition.await();
            }
            // 干活
            num ++;
            System.out.println(Thread.currentThread().getName()+"product ");
            condition.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void decr() {
        lock.lock();
        try {
            while (num ==0) {
                condition.await();
            }
            // 干活
            num --;
            System.out.println(Thread.currentThread().getName()+"comsumer ");
            condition.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}
public class ProductComsumerDemo1 {
    public static void main(String[] args) {
        Resource resource = new Resource();

        for (int i=0;i<5;i++) {
            new Thread(()->{
                resource.incr();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                resource.decr();
            },"t"+i).start();
        }
    }
}
